import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/pages/information/station/view/status.dart';
import 'package:flutter_smart_heating/ui/src/bmap.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class EstateMapView extends StatefulWidget {
  const EstateMapView({
    super.key,
    this.companyId,
    this.companyName,
    this.onClosed,
    this.onReady,
  });
  final dynamic companyId;
  final dynamic companyName;
  final Function? onClosed;
  final Function? onReady;

  @override
  State<EstateMapView> createState() => _EstateMapViewState();
}

class _EstateMapViewState extends State<EstateMapView> {
  BMFCoordinate center = BMFCoordinate(9.917215, 116.380341);
  late BMFMapController mapController;
  Map<String, dynamic> company = {};
  bool loading = true;
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getCenterPoint(path) {
    var x = 0.0;
    var y = 0.0;
    for (var i = 0; i < path.length; i++) {
      x = x + path[i]['longitude'];
      y = y + path[i]['latitude'];
    }
    x = x / path.length;
    y = y / path.length;
    return BMFCoordinate(y, x);
  }

  fetchStation() async {
    var res = await Http.instance.post('/api/basic/estate/location', data: {
      'company_id': widget.companyId,
    });
    loading = false;
    if (res.code == 1) {
      company = res.data['company'];
      mapController.setCenterCoordinate(
        res.data['data'].isEmpty
            ? BMFCoordinate(
                res.data['center']['lat'],
                res.data['center']['lng'],
              )
            : getCenterPoint(res.data['data']),
        false,
      );
      List<BMFMarker> markers = [];
      for (var item in res.data['data']) {
        double latitude = item['latitude'];
        double longitude = item['longitude'];

        // /// text经纬度信息
        BMFCoordinate position = BMFCoordinate(latitude, longitude);
        center = position;
        BMFMarker marker = BMFMarker.icon(
          position: position,
          customMap: item,
          centerOffset: Platform.isIOS ? BMFPoint(0, 0.6) : BMFPoint(0, 45),
          identifier: '${item['id']}',
          icon: 'res/images/marker-overly.png',
          canShowCallout: false,
          zIndex: 2,
        );
        markers.add(marker);

        Map<String, Color> colors = {
          'primary': UiTheme.primary,
          'online': Colors.green,
          'offline': Colors.red,
          'abnormal': Colors.orange,
        };

        /// 构造text
        BMFText bmfText = BMFText(
          text: ' ${item['icon'] ?? '◉'} ${item['label']} ',
          paragraphSpacing: 10,
          position: position,
          bgColor: colors[item['status']] ?? UiTheme.primary,
          fontColor: Colors.white,
          fontSize: Platform.isIOS ? 15 : 30,
          alignment: BMFTextAlignment.center,
          typeFace: BMFTypeFace(
            textStype: BMFTextStyle.BOLD,
          ),
          lineSpacing: 10,
          rotate: 0,
        );

        /// 添加text
        mapController.addText(bmfText);
      }
      mapController.addMarkers(markers);
    }

    setState(() {
      center;
      company;
    });
    await 0.3.delay();
    Map<String, BMFParticleEffectType> effects = {
      "Fireworks": BMFParticleEffectType.Fireworks,
      "Flower": BMFParticleEffectType.Flower,
      "PUnknow": BMFParticleEffectType.PUnknow,
      "RainStorm": BMFParticleEffectType.RainStorm,
      "SandStorm": BMFParticleEffectType.SandStorm,
      "Smog": BMFParticleEffectType.Smog,
      "Snow": BMFParticleEffectType.Snow
    };
    if (effects[res.data['effect']] != null && Platform.isIOS) {
      mapController.showParticleEffect(effects[res.data['effect']]!);
    }
    widget.onReady?.call();
  }

  bool showStation = false;
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Opacity(
          opacity: loading ? 0 : 1,
          child: BmapWidget(
            onBMFMapCreated: (controller) {
              mapController = controller;
              fetchStation();

              /// 地图marker点击回调
              mapController.setMapClickedMarkerCallback(
                  callback: (BMFMarker marker) {
                StationStatusView.show(context,
                    id: marker.customMap?['station_id']);
              });
            },
            mapOptions: BMFMapOptions(
              center: center,
              overlookEnabled: false,
              rotateEnabled: false,
              zoomLevel: 16,
              mapPadding: BMFEdgeInsets(
                left: 30,
                top: 0,
                right: 30,
                bottom: 0,
              ),
            ),
          ),
        ),
        if (loading) const Align(child: UiLoading()),
      ],
    );
  }
}
